Shader "Unlit/AnimationShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Rows ("Rows", int) = 4
        _Columns ("Columns", int) = 4
        _Speed ("Speed", float) = 1
    }
    SubShader
    {
        Tags
        {
            "RenderType"="Opaque"
        }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_fog
            #include "UnityCG.cginc"

            struct appdata_t
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            int _Rows;
            int _Columns;
            float _Speed;

            v2f vert(appdata_t v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                //将一张大图平均分为 _Rows * _Columns 张小图
                float index = floor(_Time.y * _Speed) % (_Rows * _Columns);
                //当前行数
                float rowIndex = floor(index / _Columns);
                //当前列数
                float columnIndex = floor(index % _Columns);
                //归一化，算起始位置
                float2 beginPos = float2(columnIndex / _Columns, 1 - (rowIndex / _Rows));
                float2 uvScale = float2(1.0 / _Columns, 1.0 / _Rows);
                //这里是将小图缩小
                return tex2D(_MainTex, i.uv * uvScale + beginPos);
            }
            ENDCG
        }
    }
}